﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace M.Warehouse.Repository
{
    /// <summary>
    /// 仓储实现
    /// </summary>
    public class WRepository<T>:IWRepository<T> where T : class,new()
    {
        /// <summary>
        /// 上下文
        /// </summary>
        private readonly WEFDbContext _dbContext;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="dbContext"></param>
        public WRepository(WEFDbContext dbContext) 
        {
            _dbContext = dbContext;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            await _dbContext.AddAsync(entity);
            return await _dbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await _dbContext.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 带条件显示
        /// </summary>
        /// <param name="expre"></param>
        /// <returns></returns>
        public Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return _dbContext.Set<T>().Where(expre).ToListAsync();
        }
        /// <summary>
        /// 显示单条
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetModelAsync(int id)
        {
            return await _dbContext.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Update(T entity)
        {
             _dbContext.Update(entity);
            return await _dbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public async Task<int> UpdateRange(List<T> entities)
        {
            _dbContext.UpdateRange(entities);
            return await _dbContext.SaveChangesAsync();
        }
    }
}
